package cn.edu.dgut.css.sai.creatspringbootdemo;

import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.http.MediaType;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import static org.hamcrest.Matchers.equalTo;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

import java.util.Arrays;

@SpringBootApplication
public class CreatSpringBootDemoApplication {

    public static void main(String[] args) {

        SpringApplication.run(CreatSpringBootDemoApplication.class, args);
    }


    @RestController
    static class HelloWorldController {
        @RequestMapping("hello")
        String index(){
            return "你好";
        }

    }

    @Bean
    public CommandLineRunner commandLineRunner(ApplicationContext ctx){
        return arg -> {
            System.out.println("由SpringBoot注册的所有Bean：");

            String [] beanNames = ctx.getBeanDefinitionNames();
            Arrays.sort(beanNames);
            for(String beanName : beanNames){
                System.out.println(beanName);
            }
        };
    }

    @SpringBootTest
    @AutoConfigureMockMvc
    class Lab1ApplicationTests {

        @Autowired
        private MockMvc mockMvc;

        @Test
        public void getHello() throws Exception{
            //status,content,equalTo均为静态方法
            mockMvc.perform(MockMvcRequestBuilders.get("/hello").accept(MediaType.APPLICATION_JSON))
                    .andExpect(status().isOk())
                    .andExpect(content().string(equalTo("Hello, spring boot!")));

        }
    }


}

